/**
 * creep繁衍
 */

const err = require("./error");

module.exports = function (info) {
    let roomname = info.roomname;
    // 深拷贝creeps
    let creeps = Object.create(info.creeps);
    for (let creep in creeps) {
        creeps[creep] = Object.create(creeps[creep])
    }
    // 检查creep的数量
    for (let i in Game.creeps) {
        let creep = Game.creeps[i];
        if ((creep.room.name == roomname && !/^g_/.test(i)) ||
            (/^g_/.test(i) && creep.memory.roomname == roomname)) {
            // if (creeps[creep.memory.role])
            creeps[creep.memory.role].num--;
        }
    }
    if (Memory.log) {
        console.log(info.roomname)
        for (let creep in creeps) {
            console.log(creep, info.creeps[creep].num, creeps[creep].num);
        }
    }

    // 繁衍不够的creep
    for (let creep in creeps) {
        if (creeps[creep].num > 0) {
            if (creep == 'g_carrier' &&
                ((info.creeps[creep].num - creeps[creep].num > 1 &&
                    info.creeps['g_harvester2'].num - creeps['g_harvester2'].num < 2) ||
                    (info.creeps[creep].num - creeps[creep].num > 4 &&
                        info.creeps['g_harvester2'].num - creeps['g_harvester2'].num < 3))) {
                continue;
            }
            let newName = creep + '_' + Game.time;
            console.log('Will spawn new ' + creep + ' in ' + roomname + ': ' + newName);
            let spawn = Game.rooms[roomname].find(FIND_STRUCTURES, {
                filter: (structure) => structure.structureType == STRUCTURE_SPAWN
            })[0];
            if (spawn) {
                err(spawn.spawnCreep, spawn.spawnCreep(creeps[creep].body,
                    newName, { memory: { role: creep, roomname: roomname } }));
            }
            else {
                console.log("no spawn!");
            }
            // 保证繁衍顺序
            break;
        }
    }
};